package com.css.zfzx.sjcj.modules.drill.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.CheckObjFields;
import com.css.zfzx.sjcj.common.utils.LocationUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.drill.Entity.QhY02Entity;
import com.css.zfzx.sjcj.modules.drill.Entity.QhY04Entity;
import com.css.zfzx.sjcj.modules.drill.Entity.vo.*;
import com.css.zfzx.sjcj.modules.drill.repository.*;
import com.css.zfzx.sjcj.modules.drill.service.*;
import com.css.zfzx.sjcj.modules.drill.viewobjects.QhY02QueryParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author Li Helei
 * @date 2021/1/16 10:44
 */
@Slf4j
@Service
public class QhY02ServiceImpl implements QhY02Service {

	@Autowired
    private QhY02Repository qhY02Repository;
    @Autowired
    private QhY04Repository qhY04Repository;
    @Autowired
    private QhY04Service qhY04Service;
    @Autowired
    private QhY05Repository qhY05Repository;
    @Autowired
    private QhY05Service qhY05Service;
    @Autowired
    private QhY06Repository qhY06Repository;
    @Autowired
    private QhY06Service qhY06Service;
    @Autowired
    private QhY08Repository qhY08Repository;
    @Autowired
    private QhY08Service qhY08Service;
    @Autowired
    private QhY18Repository qhY18Repository;
    @Autowired
    private QhY18Service qhY18Service;
    @Autowired
    private QhY02NativeRepository qhY02NativeRepository;

    @Override
    public JSONObject queryQhY02s(QhY02QueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0){
            sort= CheckObjFields.propertyChange(sort);
        }
        Page<QhY02Entity> qhY02Page = this.qhY02NativeRepository.queryQhY02s(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhY02Page);
        return jsonObject;
    }

    @Override
    public JSONObject queryExpertQhY02s(QhY02QueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0){
            sort= CheckObjFields.propertyChange(sort);
        }
        Page<QhY02Entity> qhY02Page = this.qhY02NativeRepository.queryExpertQhY02s(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhY02Page);
        return jsonObject;
    }

    @Override
    public JSONObject queryQhY02s(QhY02QueryParams queryParams) {
        List<QhY02Entity> qhY02List = this.qhY02NativeRepository.listQhY02s(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhY02List);
        return jsonObject;
    }


    @Override
    public QhY02Entity getQhY02(String id) {
        QhY02Entity qhY02 = this.qhY02Repository.findByIdAndIsValid(id,"1");
        return qhY02;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhY02Entity saveQhY02(QhY02Entity qhY02) {
        String uuid = UUIDGenerator.getUUID();
        qhY02.setId(uuid);
        qhY02.setDataState("4");
        qhY02.setIsValid("1");
        String userId = PlatformSessionUtils.getUserId();
        if (StringUtils.isEmpty(userId)){
            throw new RuntimeException("场地与区划质检创建数据时获取用户异常！");
        }
        qhY02.setCreateUser(userId);
        qhY02.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhY02Repository.save(qhY02);
        return qhY02;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhY02Entity updateQhY02(QhY02Entity qhY02) {
        QhY02Entity qhY02Entity = qhY02Repository.findByIdAndIsValid(qhY02.getId(), "1");
        String userId = PlatformSessionUtils.getUserId();
        if (StringUtils.isEmpty(userId)){
            throw new RuntimeException("场地与区划质检修改数据获取用户异常！");
        }
        UpdateUtil.copyNullProperties(qhY02Entity, qhY02);
        qhY02.setUpdateUser(PlatformSessionUtils.getUserId());
        qhY02.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhY02Repository.save(qhY02);
        return qhY02;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhY02s(List<String> ids) {
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for(QhY02Entity qhY02 : qhY02List) {
                qhY02.setIsValid("0");
                this.qhY02Repository.save(qhY02);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQh(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        this.qhY04Repository.deleteAllByDrillIdIn(idList);
        this.qhY05Repository.deleteAllByDrillIdIn(idList);
        this.qhY06Repository.deleteAllByDrillIdIn(idList);
        this.qhY08Repository.deleteAllByDrillIdIn(idList);
        this.qhY18Repository.deleteAllByDrillIdIn(idList);
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for(QhY02Entity qhY02 : qhY02List) {
                qhY02.setIsValid("0");
                this.qhY02Repository.save(qhY02);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhY02(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for(QhY02Entity qhY02 : qhY02List) {
                this.qhY02Repository.save(qhY02);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public JSONObject checkCoordinate(String ids) {
        List<String> errorIds = new ArrayList<>();
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for(QhY02Entity qhY02 : qhY02List) {
                double lon = Double.parseDouble(qhY02.getLongitude());
                double lat = Double.parseDouble(qhY02.getLatitude());
                String province = qhY02.getProvince();
                String city = qhY02.getCity();
                String area = qhY02.getArea();
                //校验
                if((lon < 73.0000 || lon > 136.0000) || (lat < 5.0000 || lat > 54.0000)) {
                    errorIds.add(qhY02.getId());
                    continue;
                }
                Map<String, String> coordRes = LocationUtil.getLocationInfoByTD(lon,lat);
                if(!province.equals(coordRes.get("province")) ||
                        !city.equals(coordRes.get("city")) ||
                        !area.equals(coordRes.get("county"))) {
                    errorIds.add(qhY02.getId());
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("data",errorIds);
        if(errorIds.size() > 0) {
            json.put("message", "共" + errorIds.size() + "条数据校验未通过");
        } else {
            json.put("message", "数据校验通过");
        }
        return json;
    }

    @Override
    public JSONObject dataQualityCheckAll(String ids) {
        JSONObject res = new JSONObject();
        List<String> idList = Arrays.asList(ids.split(","));
        String drillSynthesizeCode="";//存储质检不通过的钻孔综合编号的集合，用逗号分割
        for(String id : idList) {
            //查询钻井概况
            List<QhY02Entity> qhY02List = this.qhY02Repository.findByIdAndDataStateAndIsValid(id,"0","1");
            if(qhY02List.size() < 1) {
                continue;
            }
            for (QhY02Entity qhY02 : qhY02List){
                //Y02表
                qhY02= this.dataQualityCheck(qhY02);

                String drillId = qhY02.getId();
                //Y04表
                List<QhY04Vo> qhY04VoList= qhY04Service.dataQualityCheck(drillId);
                if(!qhY04VoList.isEmpty()&&qhY04VoList.size()>0){
                    for (QhY04Vo qhY04Vo:qhY04VoList){
                        if (qhY04Vo.getDataState()=="1"&& qhY02.getDataState()=="1"){
                            //qhY02.setDataState(qhY04Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion()+qhY04Vo.getQualityOpinion());
                            continue;
                        }else if(qhY04Vo.getDataState()=="1"&& qhY02.getDataState()=="2"){
                            qhY02.setDataState(qhY04Vo.getDataState());
                            qhY02.setQualityOpinion(qhY04Vo.getQualityOpinion());
                            continue;
                        }
                    }
                }else {
                    if (qhY02.getDataState()=="1"){
                        //qhY02.setDataState("1");
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion()+"Y04数据不能为空;");
                    }else {
                        qhY02.setDataState("1");
                        qhY02.setQualityOpinion("Y04数据不能为空;");
                    }
                }
                //Y05表
                List<QhY05Vo> qhY05VoList= qhY05Service.dataQualityCheck(drillId);
                if(!qhY05VoList.isEmpty()&&qhY05VoList.size()>0){
                    for (QhY05Vo qhY05Vo:qhY05VoList){
                        if (qhY05Vo.getDataState()=="1"&& qhY02.getDataState()=="1"){
                            //qhY02.setDataState(qhY05Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion()+qhY05Vo.getQualityOpinion());
                            continue;
                        }else if (qhY05Vo.getDataState()=="1"&& qhY02.getDataState()=="2"){
                            qhY02.setDataState(qhY05Vo.getDataState());
                            qhY02.setQualityOpinion(qhY05Vo.getQualityOpinion());
                            continue;
                        }
                    }
                }
                //Y06表
                List<QhY06Vo> qhY06VoList= qhY06Service.dataQualityCheck(drillId);
                if(!qhY06VoList.isEmpty()&&qhY06VoList.size()>0){
                    for (QhY06Vo qhY06Vo:qhY06VoList){
                        if (qhY06Vo.getDataState()=="1"&& qhY02.getDataState()=="1"){
                            //qhY02.setDataState(qhY06Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion()+qhY06Vo.getQualityOpinion());
                            continue;
                        }else if (qhY06Vo.getDataState()=="1"&& qhY02.getDataState()=="2"){
                            qhY02.setDataState(qhY06Vo.getDataState());
                            qhY02.setQualityOpinion(qhY06Vo.getQualityOpinion());
                            continue;
                        }
                    }
                }else {
                    if (qhY02.getDataState()=="1"){
                        //qhY02.setDataState("1");
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion()+"Y06数据不能为空;");
                    }else {
                        qhY02.setDataState("1");
                        qhY02.setQualityOpinion("Y06数据不能为空;");
                    }
                }
                //Y08表
                List<QhY08Vo> qhY08VoList= qhY08Service.dataQualityCheck(drillId);
                if(!qhY08VoList.isEmpty()&&qhY08VoList.size()>0){
                    for (QhY08Vo qhY08Vo:qhY08VoList){
                        if (qhY08Vo.getDataState()=="1"&& qhY02.getDataState()=="1"){
                            //qhY02.setDataState(qhY08Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion()+qhY08Vo.getQualityOpinion());
                            continue;
                        }else if (qhY08Vo.getDataState()=="1"&& qhY02.getDataState()=="2"){
                            qhY02.setDataState(qhY08Vo.getDataState());
                            qhY02.setQualityOpinion(qhY08Vo.getQualityOpinion());
                            continue;
                        }
                    }
                }
                //Y18表
                QhY18Vo qhY18Vo= qhY18Service.dataQualityCheck(drillId);
                if(!PlatformObjectUtils.isEmpty(qhY18Vo)){
                    if (qhY18Vo.getDataState()=="1"&& qhY02.getDataState()=="1"){
                        //qhY02.setDataState(qhY18Vo.getDataState());
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion()+qhY18Vo.getQualityOpinion());
                    }else if (qhY18Vo.getDataState()=="1"&& qhY02.getDataState()=="2"){
                        qhY02.setDataState(qhY18Vo.getDataState());
                        qhY02.setQualityOpinion(qhY18Vo.getQualityOpinion());
                    }
                }else {
                    if (qhY02.getDataState()=="1"){
                        //qhY02.setDataState("1");
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion()+"Y18数据不能为空;");
                    }else {
                        qhY02.setDataState("1");
                        qhY02.setQualityOpinion("Y18数据不能为空;");
                    }
                }
                this.updateQhY02(qhY02);
                if (qhY02.getDataState()=="1"){
                    drillSynthesizeCode=drillSynthesizeCode+","+qhY02.getDrillSynthesizeCode();
                }
                //res.put("mag","综合钻孔编号:"+qhY02.getDrillSynthesizeCode()+","+qhY02.getQualityOpinion());
            }
        }
        if (!StringUtils.isEmpty(drillSynthesizeCode)){
            drillSynthesizeCode="综合钻孔编号:"+drillSynthesizeCode;
            res.put("mag", drillSynthesizeCode);
        }
        return res;
    }
    public QhY02Entity dataQualityCheck(QhY02Entity qhY02){
        JSONObject res = new JSONObject();

        try {
            //检查字段值不为空
            StringBuilder errorMsg = new StringBuilder();
            Map<String, String> methods = new HashMap<>();
            setCheckFields(methods);

            ServerUtil.checkFieldNull(qhY02, methods, errorMsg);

            if(errorMsg.length()>0|| org.apache.commons.lang3.StringUtils.isNotEmpty(errorMsg.toString())) {
                qhY02.setQualityOpinion("Y02的"+errorMsg.toString());
                qhY02.setDataState("1");
                return qhY02;
            }
            //检查字段属性
            if (qhY02.getLongitude().length()-qhY02.getLongitude().indexOf(".")-1<4){
                ServerUtil.addErrorMsg(errorMsg, "孔位经度", "小数点后保留至少4位");
            }
            if (qhY02.getLatitude().length()-qhY02.getLatitude().indexOf(".")-1<4){
                ServerUtil.addErrorMsg(errorMsg, "孔位纬度", "小数点后保留至少4位");
            }
            String drillSynthesizeCode=qhY02.getDrillSynthesizeCode();
            Double longitude=Double.parseDouble(qhY02.getLongitude());
            Double latitude=Double.parseDouble(qhY02.getLatitude());
            Double drillDepth=qhY02.getDrillDepth();

            String str=drillSynthesizeCode.substring(6, 8);
            if (!(drillSynthesizeCode.length()==11||"SK".equals(str)||"PK".equals(str))){
                ServerUtil.addErrorMsg(errorMsg, "钻孔综合编号", "不符合规范");
            }
            if(longitude < 73.0000 || longitude > 136.0000) {
                ServerUtil.addErrorMsg(errorMsg, "孔位经度", "73.0000~136.0000之间");
            }
            if(latitude < 5.0000 || latitude > 54.0000) {
                ServerUtil.addErrorMsg(errorMsg, "孔位纬度", "5.0000~54.0000之间");
            }
            if (drillDepth<0){
                ServerUtil.addErrorMsg(errorMsg, "钻孔深度", "大于0");
            }

            String strErrorMsg = errorMsg.toString();
            if(!strErrorMsg.isEmpty()) {
                qhY02.setQualityOpinion("Y02的"+strErrorMsg);
                qhY02.setDataState("1");
            } else {
                qhY02.setQualityOpinion("系统自动质检通过");
                qhY02.setDataState("2");
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }
        return qhY02;
    }
    private void setCheckFields(Map<String,String> methods){
        methods.put("drillSynthesizeCode", "钻孔综合编号");
        methods.put("drillDependProject", "钻孔依托的项目");
        methods.put("projectCompleteInstitution", "项目完成单位");
        methods.put("projectCompleteDate", "项目完成时间");
        methods.put("projectPrincipal", "项目负责人");
        methods.put("drillConstructionInstitution", "钻孔勘察单位");
        methods.put("drillConstructionPrincipal", "钻孔勘察负责人");
        methods.put("constructionStartDate", "勘察施工日期");
        methods.put("constructionReportDate", "勘察报告日期");
        methods.put("drillCode", "钻孔编号");
        methods.put("longitude", "孔位经度（°）");
        methods.put("latitude", "孔位纬度（°）");
        methods.put("drillDepth", "钻孔深度");
        methods.put("elevation", "地面高程");
        methods.put("province", "钻孔所在省级行政区");
        methods.put("city", "钻孔所在地市级行政区");
        methods.put("area", "钻孔所在县级行政区");
        methods.put("village", "钻孔所在乡级行政区");
    }
}
